import { ClockCircleOutlined } from '@ant-design/icons'
import { Popover, Tooltip, DatePicker } from 'antd'
import dayjs, { type Dayjs } from 'dayjs'
import { colors, flexCenter } from '@/desktop/styles'
import { useStreams } from '@/lib/utils'
import services from '@/services'

export function FilterByTime() {
  const [{ maxTimestamp }] = useStreams(services.externals.conditions$)
  const value = useMemo(() => (maxTimestamp !== null ? dayjs(maxTimestamp) : null), [maxTimestamp])
  function onChange(value: Dayjs | null) {
    services.externals.setConditions({
      maxTimestamp: value?.valueOf() ?? null,
    })
  }

  const content = <div css={s.content}>
    <div className="desc">只看此时间之前的联系人：</div>
    <DatePicker showTime placeholder="请选择时间" allowClear value={value} onChange={onChange} />
  </div>

  return <Popover placement="bottom" trigger="click" content={content}>
    {/* 两层浮层间需垫一层元素，不然会报 ref 错误 */}
    <div>
      <Tooltip title="按时间筛选">
        <div css={s.trigger} className={maxTimestamp !== null ? 'filtered' : ''}>
          <ClockCircleOutlined />
        </div>
      </Tooltip>
    </div>
  </Popover>
}

const s = {
  trigger: css`
    ${flexCenter};
    background-color: #f5f5f5;
    border-radius: 4px;
    color: #666;
    cursor: pointer;
    height: 34px;
    margin-left: 10px;
    width: 36px;

    &.filtered {
      color: ${colors.link};
    }
    .anticon {
      font-size: 16px;
    }
  `,
  content: css`
    .desc {
      color: #999;
      font-size: 12px;
      margin-bottom: 8px;
    }
  `,
}
